/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.webos.java.sessinfo;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import org.webos.java.base.Frame;
import org.webos.java.base.FrameType;
import org.webos.java.base.RemoteMessage;
import org.webos.java.base.workspace.Workspace;
import org.webos.java.root.Log;

/**
 *
 * @author kostya
 */

class Message{
    Date receiveDate = new Date();
    String from = "";
    String message = "";
}

@FrameType(code="chat_list", jsClass="sessinfo.ChatHistory")
public class ChatHistory extends Frame{

    private List<Message> messages = new ArrayList<Message>();

    SessionsInfo app = null;

    public ChatHistory(SessionsInfo aApplication, Workspace aWorkspace) {
        super(aApplication, aWorkspace);
        app = aApplication;
        setIcon("sessinfo_icon");
        setTitle("Chat history");
    }

    @RemoteMessage
    public JSONObject getChatLog(JSONObject object){
        try {
            JSONArray arr = new JSONArray();
            for (int i = 0; i < messages.size(); i++) {
                Message message = messages.get(i);
                JSONObject obj = new JSONObject();
                obj.put("from", message.from);
                obj.put("message", message.message);
                obj.put("receiveDate", app.sessionList.dateFormat.format(
                        app.getSession().normalizeDate(message.receiveDate)));
                arr.put(obj);
            }
            JSONObject res = new JSONObject();
            res.put("log", arr);
            return res;
        } catch (Throwable t) {
            Log.error(this, "Exception thrown: " + t.getMessage());
            t.printStackTrace();
        }
        return null;
    }

    protected void receiveMessage(String aFrom, String message){
        Message m = new Message();
        m.from = aFrom;
        m.message = message;
        messages.add(m);
        new NewMessageDialog(app, m);
    }

}
